package gomodel

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"strings"
	//"wens.com/wlw_environment/controller/src/common"
	"gitee.com/yuyuaa/easy-go-tool/gofunc"
	"os/exec"
	"runtime"
)

//可以从json文件初始化和保存回json
type JsonRelated struct {
	Parent   interface{} `json:"-" wireboxStruct:"-" gobalStruct:"-"`
	JsonPath string      `json:"-" wireboxStruct:"-" gobalStruct:"-"`
}

func (self *JsonRelated) SetUseFile(parent interface{}, js_path string) error {
	//通过json文件初始化
	self.JsonPath = js_path
	self.Parent = parent
	raw, err := ioutil.ReadFile(js_path)
	filefunc := gofunc.FileFunc{}
	if err != nil {
		log.Println("读取", js_path, "错误自动删除创建一个文件")
		path_default := strings.Replace(js_path, ".json", "_default.json", -1)
		os.Remove(js_path)
		os.Remove(path_default)
		os.Create(js_path)
		self.Save2Json() //保存到新建的文件夹中
		//复制一份到为default
		filefunc.CopyFile(js_path, path_default)
		return nil
	}
	//将配置解析到结构体中
	err = json.Unmarshal(raw, parent)
	if err != nil {
		return err
	}
	return nil
}

//将结构体设置回默认值，比如初始化用的是 gobal.json 设置回默认值就用同级目录下的gobal_default.json
func (self *JsonRelated) SetDefault() error {
	//传入的是"./config/smart/gear.json"地址那么默认json就是 "./config/smart/gear_default.json"
	path_default := strings.Replace(self.JsonPath, ".json", "_default.json", -1)
	//common.Logger.Debug(path_default)
	raw, err := ioutil.ReadFile(path_default)
	if err != nil {
		return err
	}
	//将配置解析到结构体中
	err = json.Unmarshal(raw, self.Parent)
	if err != nil {
		return err
	}
	self.Save2Json()
	return nil
}

func (self *JsonRelated) Save2Json() {
	log.Println(self.JsonPath)
	b, _ := json.MarshalIndent(self.Parent, "", "\t")
	//f, err := os.OpenFile("./config/hardware/wireBox.json", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
	f, err := os.OpenFile(self.JsonPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
	defer f.Close()
	if err != nil {
		panic(err)
	}
	f.Write(b)
	//如果是linux系统还需要sync同步
	if runtime.GOOS == "linux" {
		err = exec.Command("sync").Run()
		if err != nil {
			log.Println(err)
		}
	}
}
